import { restService } from "@/apis/rest";
import { useCrypto } from "@/hooks/useCrypto";
import { useLocalStorage } from "@/hooks/useLocalStorage";
import { RootState } from "@/store";
import { RouteRecordRaw } from "vue-router";
import { Module, MutationTree } from "vuex";
import { IUserActions, IUserGetter, IUserState } from "./types";

const state: IUserState = {
    user: JSON.parse(localStorage.getItem('bishe-user') || '{}') || [],
    asyncRoutes: [],
    rootFilePath: ''
};

const actions: IUserActions = {

}

const mutations: MutationTree<IUserState> = {
    _setAsyncRoutes: (state: IUserState, asyncRoutes: Array<RouteRecordRaw>) => {
        state.asyncRoutes = [...asyncRoutes];
    },
    // 重置userStoreState
    _resetUserStoreState: (state: IUserState) => {
        state.user = {} as IUserState['user'];
        state.asyncRoutes = [];
    },
    _setUser: (state: IUserState, user: IUserState['user']) => {
        state.user = user;
        const { encrypt } = useCrypto();
        user.username = encrypt(user.username)
        user.password = encrypt(user.password)
        useLocalStorage().setLocalStorage('bishe-user', user);
    },
    _getAndSetRootFilePath: async (state: IUserState) => {
        state.rootFilePath = await restService('file', { type: 'root' }).get();
        useLocalStorage().setLocalStorage('bishe-rootFilePath', state.rootFilePath['path']);
    },
}

const getters: IUserGetter = {
    getUserData: (state) => {
        return null;
    }

}
export const user: Module<IUserState, RootState> = {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}


